package com.email.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.email.bean.Operator;
import com.email.bussiness.IOperatorDao;
import com.email.bussiness.OperatorDao;
/**
 * 数据库连接基类<p/>
 * @author victor
 *
 */
public class DBConnection {
	private static final Log log = LogFactory.getLog(DBConnection.class);
	private static Connection conn;
	private final static String url = "jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=UTF-8";
	private final static String user = "root";
	private final static String password = "root";
	private final static String DRIVER="com.mysql.jdbc.Driver";  

	public static Connection getConnection(){
		try {
			try {
				Class.forName(DRIVER).newInstance();
				conn = DriverManager.getConnection(url, user, password);	
			}  catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}	
		} catch (SQLException e) {
			//e.printStackTrace();
			log.error("数据库连接出错。");
		}
		return conn;
	}

	public void closeConnection() {
		if (!(conn == null)) {
			try {
				conn.close();
			} catch (SQLException e) {
				//e.printStackTrace();
				log.error("数据库关闭出错。");
			}
		}
	}
	
	/**
	 * 测试数据库连接。
	 * @param args
	 */
	public static void main(String[] args){
		try {
			log.info("数据库的关闭状态： "+DBConnection.getConnection().isClosed());
			IOperatorDao operatorDao = new OperatorDao();
			Operator operator = operatorDao.findOperator("1", "000000");
			if(operator!=null)
			log.info("操作员的姓名： "+operator.getUsername());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}